﻿using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace TypeScriptJson.Generator
{
	public class Generator
	{
		private GeneratorContext _context;

		public GeneratorContext Context
		{
			get { return _context ?? (_context = new GeneratorContext()); }
			set { _context = value; }
		}

		public IContractResolver ContractResolver
		{
			get { return Context.ContractResolver; }
			set { Context.ContractResolver = value; }
		}

		public JsonSerializerSettings SerializerSettings
		{
			get { return Context.SerializerSettings; }
			set { Context.SerializerSettings = value; }
		}

		public void GenerateToSingleFile(string filename)
		{
			Context.Process();

			using (var textWriter = new StreamWriter(filename))
			{
				var codeWriter = new TypeScriptCodeWriter(textWriter);

				var typesByModule = from mapping in Context.TypeMappings.Values.Distinct()
				                    where mapping.IsGenerateDeclaration
				                    orderby mapping.ModuleName
				                    group mapping by mapping.ModuleName;

				foreach (var module in typesByModule)
				{
					if (!string.IsNullOrEmpty(module.Key))
						codeWriter.WriteStartModule(module.Key);
					foreach (var mapping in module)
						mapping.WriteTypeDeclaration(codeWriter, Context);
					if (!string.IsNullOrEmpty(module.Key))
						codeWriter.WriteEndModule();
				}
			}
		}
	}
}